package com.chuangjiangx.member.stored.web.controller;

import com.chuangjiangx.commons.CurrentThreadContext;
import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.commons.response.CamelResponse;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.domain.shared.model.PayEntry;
import com.chuangjiangx.domain.shared.model.PayType;
import com.chuangjiangx.member.stored.ddd.application.MbrPayApplication;
import com.chuangjiangx.member.stored.ddd.domain.model.MbrOrder;
import com.chuangjiangx.member.stored.ddd.domain.model.MbrOrderRepository;
import com.chuangjiangx.member.basic.web.exceptions.MbrRechargeException;
import com.chuangjiangx.member.basic.web.interceptor.Login;
import com.chuangjiangx.member.stored.web.request.PayRechargeOrderRequest;
import com.chuangjiangx.member.stored.web.request.RechargeRequest;
import com.chuangjiangx.member.stored.web.response.PayResultResponse;
import com.chuangjiangx.member.stored.web.response.QueryRechargeResultResponse;
import com.chuangjiangx.member.stored.web.response.RequestRechargeResponse;
import com.chuangjiangx.member.stored.service.H5PayService;
import com.chuangjiangx.member.stored.service.command.PayMbrRechargeOrderCommand;
import com.chuangjiangx.member.stored.service.model.RechargeOrder;
import com.chuangjiangx.member.stored.ddd.query.MbrOrderQuery;
import com.chuangjiangx.member.basic.ddd.query.MerchantInfoQuery;
import com.chuangjiangx.member.stored.ddd.dal.dto.MbrOrderRechargeResult;
import com.chuangjiangx.member.basic.ddd.dal.dto.MerchantPayConfig;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserContext;
import com.chuangjiangx.member.stored.ddd.domain.model.MbrOrderId;
import com.chuangjiangx.member.stored.ddd.domain.model.MbrOrderStatus;
import com.chuangjiangx.member.common.utils.RequestUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

/**
 * @author cj-ch
 * @date 2018/7/4 上午9:59
 */
@Slf4j
@RestController
@RequestMapping(value = "/h5/recharge")
@Api(tags = "充值",description = "充值接口")
public class RechargeController {
    @Value("${member.h5.domain}")
    private String h5Domain;
    @Value("${client.api.domain}")
    private String clientApiDomain;
    @Autowired
    private MbrPayApplication mbrPayApplication;
    @Autowired
    private MbrOrderRepository mbrOrderRepository;
    @Autowired
    private MbrOrderQuery mbrOrderQuery;
    @Autowired
    private MerchantInfoQuery merchantInfoQuery;
    @Autowired
    private H5PayService h5PayService;


    /**
     * 去充值
     * 如果商户配置的不是微信\支付宝官方渠道需要重定向获取openid
     * @param request
     * @param rechargeRequest
     * @return
     */
    @ApiOperation(value = "会员充值下单接口")
    @RequestMapping(value = "",method = RequestMethod.POST)
    @Login
    public CamelResponse<RequestRechargeResponse> recharge(
            HttpServletRequest request,
            @RequestBody @Validated RechargeRequest rechargeRequest
            ) {
        RequestRechargeResponse response = new RequestRechargeResponse();
        MbrUserContext user = (MbrUserContext) CurrentThreadContext.getCurrentUser();
        PayEntry payEntry = RequestUtils.getPayEntry(request);
        // 查询商户的支付配置
        MerchantPayConfig merchantPayConfig = merchantInfoQuery.queryPaymentConfig(payEntry, PayType.MICRO_PAY, user.getMerchantId());
        if(Objects.equals(PayEntry.WXPAY,payEntry)){
            //微信
            if(1 != merchantPayConfig.getPayChannelId() ){
                //如果微信C扫B支付渠道配置的不是微信服务商 或
                throw new MbrRechargeException("","暂不支持非微信服务商支付渠道:"+merchantPayConfig.getPayChannelId());
                //需要重定向获取openid
            } else if(StringUtils.isBlank(user.getOpenId())){
                //服务商公众号openid是空的
                //需要重定向获取openid
            }

        } else {
            throw new MbrRechargeException("","暂不支持:"+payEntry);
        }

        RechargeOrder rechargeOrder = h5PayService.mbrRechargeUnifiedOrder(user, rechargeRequest);
        response.setOrder(rechargeOrder);
        return (CamelResponse<RequestRechargeResponse>)ResponseUtils.successCamel(response);
    }



    /**
     * 支付充值订单
     * 目前只支持微信官方直连
     */
    @RequestMapping(value = "/pay-order",method = RequestMethod.POST)
    @Login
    public Response<PayResultResponse> pay(
            HttpServletRequest request,
            @RequestBody @Validated PayRechargeOrderRequest payRechargeOrderRequest
    ){
        PayResultResponse response = new PayResultResponse();
        response.setMbrOrderId(payRechargeOrderRequest.getMbrOrderId());
        MbrUserContext user = (MbrUserContext) CurrentThreadContext.getCurrentUser();
        MbrOrder mbrOrder = mbrOrderRepository.fromId(new MbrOrderId(payRechargeOrderRequest.getMbrOrderId()));
        if(null == mbrOrder){
            throw new BaseException("","订单不存在");
        }
        if(!Objects.equals(MbrOrderStatus.NOT_PAID,mbrOrder.getStatus())){
            throw new BaseException("","订单状态未处于未支付状态");
        }
        if(StringUtils.isBlank(user.getOpenId()) && StringUtils.isBlank(user.getSubOpenId())){
                throw new BaseException("","用户openid不存在");
        }
        PayEntry payEntry = RequestUtils.getPayEntry(request);

        PayMbrRechargeOrderCommand command = PayMbrRechargeOrderCommand.builder()
                .ip(RequestUtils.getRequestIp(request))
                .mbrOrderId(payRechargeOrderRequest.getMbrOrderId())
                .orderPayId(payRechargeOrderRequest.getOrderPayId())
                .payEntry(payEntry)
                .user(user)
                .build();
        h5PayService.payMbrRechargeOrder(command,response);
        return ResponseUtils.successCamel(response);
    }


    /**
     * 充值回调
     * @param mbrOrderId
     * @param websocketId
     * @param request
     * @return
     */
    @ApiOperation(value = "会员充值回调接口",httpMethod = "GET")
    @RequestMapping(value = "/call-back")
    public Response callbackUrl(
            @RequestParam Long mbrOrderId,
            @RequestParam(required = false) String websocketId,
            HttpServletRequest request) {
        //TODO...支付成功回调处理
        log.info("充值回调=====");
        log.info("mbrOrderId:{},websocketId:{}",mbrOrderId,websocketId);
        try {
            log.info("post数据:{}",IOUtils.toString(request.getInputStream(),"utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseUtils.successCamel();
    }

    /**
     * 查询充值结果
     * @param id
     * @return
     */
    @ApiOperation(value = "查询充值结果",produces = "application/json")
    @RequestMapping(value = "/search-result/{id}",method = RequestMethod.GET)
    @Login
    public CamelResponse<QueryRechargeResultResponse> searchResult(
            @PathVariable Long id
    ){
        //
        MbrOrderRechargeResult result = mbrOrderQuery.queryRechargeResult(id);
        if(null != result){
            if(Objects.equals(MbrOrderStatus.PAID.value,result.getStatus())){
                QueryRechargeResultResponse res = new QueryRechargeResultResponse();
                BeanUtils.copyProperties(result,res);
                return (CamelResponse<QueryRechargeResultResponse>) ResponseUtils.successCamel(res);
            }
        }
        return (CamelResponse<QueryRechargeResultResponse>) ResponseUtils.errorCamel("","");
    }


}
